package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.constants.RedisConstant;
import com.hmdp.dto.UserDTO;
//import com.hmdp.entity.User;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
//import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("刷新拦截器执行了，直接一个刷新用户登录有效时间");
        String token =  request.getHeader("authorization");
        if(StrUtil.isBlank(token)){
            log.info("StrUtil.isBlank");
//            response.setStatus(401);
            return true;
        }
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstant.LOGIN_TOKEN_KEY + token);

        if(userMap.isEmpty()){
            log.info("userMap.isBlank");
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

//        log.info("刷新拦截器执行了，直接一个刷新用户登录有效时间");
        UserHolder.saveUser(userDTO);

        stringRedisTemplate.expire(RedisConstant.LOGIN_TOKEN_KEY + token, RedisConstant.CACHE_SHOP_TTL + (long)(Math.random() * 10), TimeUnit.MINUTES);

        return true;
    }


}
